<template>
  <div class="app-container">
    <el-row style="padding-bottom:10px">
      <el-col :span="4">
        <strong style="font-size: 20px;">
          财务汇总
        </strong>
      </el-col>
      <el-col :span="20" align="right">
        <span style="margin-right: .5em">
          <el-date-picker
            v-model="search.date"
            type="daterange"
            placeholder="营业日"
            size="medium"
            :editable="false"
            :clearable="false"
            value-format="yyyy/MM/dd"
            @change="dataProcessor()"
          />
        </span>
      </el-col>
    </el-row>

    <div class="background">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <div class="detail">
              <i class="el-icon-document-remove" />
              订单实收/订单营收
              <div class="text">
                ￥<span style="color:#19be6b">{{ balance.actualEarns }}/{{ balance.earns }}</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <div class="detail">
              <i class="el-icon-s-order" />
              可发放余额/期初数
              <div class="text">
                <span style="color:#909399">{{ balance.user }}</span>
                <span>/</span>
                <span>{{ balance.log }}</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <div class="detail">
              <i class="el-icon-bank-card" />
              收银系统入金/pos机刷卡入金
              <div class="text">
                <span style="color:#fa3534">{{ balance.amount }}</span>
                <span>/</span>
                <span style="color:#2979ff">{{ balance.posAmount }}</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <div class="detail">
              <i class="el-icon-bank-card" />
              入金手续费
              <div class="text">
                <!-- ￥<span style="color:#fa3534">{{ balance.posAmount }}</span>
                <span>/</span> -->
                <span style="color:#ff9900">{{ balance.fee }}</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-row>
      <div style="height:10px" />
      <div class="box">
        <div style="width:50%">
          <div>分账项：</div>
          <div v-for="(item,index) in items" :key="index" class="item" >
            <span style="width:30%">{{ types[item.profitType] }}</span>
            <span style="width:30%">{{ item.amount }}</span>
            <el-button type="text" @click="toSettleItem(item)">查看明细</el-button>
          </div>
        </div>
        <div style="width:50%">
          <div>发放项：</div>
          <div class="item" >
            <span style="width:30%">手动工资发放</span>
            <span style="width:30%">{{ transactions.salary }}</span>
            <el-button type="text" @click="toSalary()">查看明细</el-button>
          </div>
          <div class="item" >
            <span style="width:30%">考勤工资发放</span>
            <span style="width:30%">{{ transactions.salarySettle }}</span>
            <el-button type="text" @click="toSalary()">查看明细</el-button>
          </div>
          <div class="item" >
            <span style="width:30%">导入发放</span>
            <span style="width:30%">{{ transactions.upload }}</span>
            <el-button type="text" @click="toUpload()">查看明细</el-button>
          </div>
        </div>
      </div>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      store: null,
      search: {
        date: []
      },
      balance: {
        earns: 0,
        amount: 0,
        fee: 0,
        actualEarns: 0,
        posAmount: 0,
        user: 0,
        log: 0
      },
      transactions: {
        salary: 0,
        upload: 0,
        salarySettle: 0
      },
      items: [],
      types: {
        0: '酒代分成',
        1: '管理员分成',
        2: '平台分成',
        3: '负责人分成',
        4: '场所分成',
        5: '资源公司分成',
        6: '队长分成',
        7: '经纪人分成',
        8: '提成',
        9: '补贴',
        10: '工资',
        11: '订台分成',
        12: '服务员分成',
        100: '剩余余额',
        999: '平台手续费'
      }
    }
  },
  async created() {
    const today = new Date()
    const yesterday = new Date(today.getTime() - 86400000)
    const startTime = `${yesterday.getFullYear()}/${yesterday.getMonth() + 1}/${yesterday.getDate()}`
    this.search.date.push(startTime)
    this.search.date.push(startTime)
    const user = await this.axios.get(`/api/user`, { params: {
      '@expands': `['entity.officer.store']`
    }})
    this.store = user.data.officer?.__metadata.store?.__metadata
    if (!this.store.user) {
      this.$message.error('获取主账号信息失败！')
      return
    }
    this.dataProcessor()
  },
  methods: {
    toSalary() {
      this.$router.push({
        path: '/officer-salary/list',
        query: { date: [this.search.date[0], this.search.date[1]] }
      })
    },
    toUpload() {
      this.$router.push({
        path: '/officer-upload-transaction/list',
        query: { date: [this.search.date[0], this.search.date[1]] }
      })
    },
    toSettleItem(item) {
      let nextDate = new Date(new Date(this.search.date[1]).getTime() + 86400000)
      nextDate = `${nextDate.getFullYear()}/${nextDate.getMonth() + 1}/${nextDate.getDate()}`
      this.$router.push({
        path: '/officer-settle-item/list',
        query: { date: [this.search.date[0], nextDate], profitType: item.profitType }
      })
    },
    dataProcessor() {
      this.loading = true
      const promise = []
      // 默认选择结束日期的第二天(即按营业天来计算)
      let nextDate = new Date(new Date(this.search.date[1]).getTime() + 86400000)
      nextDate = `${nextDate.getFullYear()}/${nextDate.getMonth() + 1}/${nextDate.getDate()}`
      // table数据
      promise.push(
        // 总营收
        this.axios.get(`/officer/stores/statistics`, { params: {
          after: `${this.search.date[0]} 08:00:00`,
          before: `${nextDate} 07:59:59`
        }}).then((res) => {
          console.log('营收', res.data)
          if (res.data) {
            this.balance.earns = res.data.earns
            this.balance.actualEarns = res.data.actualEarns
          } else {
            this.balance.earns = 0
            this.balance.actualEarns = 0
          }
        })
      )

      // 查呢个store对应的所有pos设备，并且查入金账户，进行手续费核查
      this.axios.get(`/officer/fuiou-pos-devices`).then((res) => {
        console.log(123123, res.data)
        const targetUsers = [this.store.user.id]
        for (var i of res.data) {
          targetUsers.push(i.targetUser.id)
        }
        let depositFilter = ''
        let transactionFilter = ''
        for (var j in targetUsers) {
          if (parseInt(j) === 0) {
            transactionFilter = ` (entity.getFrom().getId() == ${targetUsers[j]}`
            depositFilter = ` (entity.getUser().getId() == ${targetUsers[j]}`
          } else {
            transactionFilter += ` || entity.getFrom().getId() == ${targetUsers[j]}`
            depositFilter += ` || entity.getUser().getId() == ${targetUsers[j]}`
          }
          if (parseInt(j) === targetUsers.length - 1) {
            transactionFilter += ')'
            depositFilter += ')'
          }
        }
        this.axios.get(`/officer/deposits`, { params: {
          '@filter': `entity.getType() != 'interior' 
                   && entity.getStatus() == 1 && entity.getCreatedTime() >= datetime.get('${this.search.date[0]} 08:00:00') 
                   && entity.getCreatedTime() <= datetime.get('${nextDate} 07:59:59') 
                   && ${depositFilter}`,
          '@select': `SUM(entity.amount) as amount, entity.type`,
          '@groupBy': 'entity.type'
        }}).then((res) => {
          console.log('deposits', res.data)
          let liansheng = 0
          let pos = 0
          for (var i of res.data) {
            if (i.type === 'liansheng') {
              liansheng += parseFloat(i.amount)
            } else {
              pos += parseFloat(i.amount)
            }
          }
          this.balance.amount = liansheng.toFixed(2)
          this.balance.posAmount = pos.toFixed(2)
        })

        // 手续费
        this.axios.get(`/officer/transactions`, { params: {
          '@filter': `entity.getType() == "deposit-fee"
                    && ${transactionFilter}
                    && entity.getCreatedTime() >= datetime.get('${this.search.date[0]} 08:00:00') 
                    && entity.getCreatedTime() <= datetime.get('${nextDate} 07:59:59')`,
          '@select': `SUM(entity.amount) as amount`
        }}).then((res) => {
          if (res.data.length > 0 && res.data[0].amount) {
            this.balance.fee = res.data[0].amount
          } else {
            this.balance.fee = 0
          }
        })
      })

      // 可发放余额
      this.axios.get(`/officer/balances`, { params: {
        '@filter': `entity.getUser().getId() == ${this.store.user.id}`
      }}).then(res => {
        if (res.data.length > 0 && res.data[0].amount) {
          this.balance.user = res.data[0].amount
        } else {
          this.balance.user = 0
        }
      })

      // 期初数
      this.axios.get(`/officer/balance-logs`, { params: {
        '@filter': `entity.getUser().getId() == ${this.store.user.id}
                 && entity.getCreatedTime() <= datetime.get('${this.search.date[0]} 20:00:00')`,
        '@order': 'entity.id|DESC',
        limit: 1
      }}).then(res => {
        if (res.data.length > 0 && res.data[0].after) {
          this.balance.log = res.data[0].after
        } else {
          this.balance.log = 0
        }
      })

      promise.push(
        // 工资发放 导入发放
        this.axios.get(`/officer/transactions`, { params: {
          '@filter': `entity.getFrom().getId() == ${this.store.user.id}
                    && entity.getCreatedTime() >= datetime.get('${this.search.date[0]} 08:00:00') 
                    && entity.getCreatedTime() <= datetime.get('${nextDate} 07:59:59')`,
          '@select': `SUM(entity.amount) as amount, entity.type as type`,
          '@groupBy': `entity.type`
        }}).then((res) => {
          console.log('支出', res.data)
          this.transactions = {
            salary: 0,
            upload: 0,
            salarySettle: 0
          }
          if (res.data.length > 0) {
            const salary = res.data.find(v => v.type === 'salary')
            if (salary && salary.amount) {
              this.transactions.salary += Number(salary.amount)
            }
            const upload = res.data.find(v => v.type === 'upload')
            if (upload && upload.amount) {
              this.transactions.upload += Number(upload.amount)
            }
            let total = 0
            const salarySettle = res.data.find(v => v.type === 'salary-settle')
            const salarySettleLeader = res.data.find(v => v.type === 'salary-settle-leader')
            const salarySettleBorker = res.data.find(v => v.type === 'salary-settle-borker')
            if (salarySettle && salarySettle.amount) {
              total += Number(salarySettle.amount)
            }
            if (salarySettleLeader && salarySettleLeader.amount) {
              total += Number(salarySettleLeader.amount)
            }
            if (salarySettleBorker && salarySettleBorker.amount) {
              total += Number(salarySettleBorker.amount)
            }
            this.transactions.salarySettle = total.toFixed(2)
          } else {
            this.transactions.salary = 0
            this.transactions.upload = 0
            this.transactions.salarySettle = 0
          }
        })
      )

      promise.push(
        // 工资发放 导入发放
        this.axios.get(`/officer/transactions`, { params: {
          '@filter': `entity.getTo().getId() == ${this.store.user.id}
                    && entity.getCreatedTime() >= datetime.get('${this.search.date[0]} 08:00:00') 
                    && entity.getCreatedTime() <= datetime.get('${nextDate} 07:59:59')`,
          '@select': `SUM(entity.amount) as amount, entity.type as type`,
          '@groupBy': `entity.type`
        }}).then((res) => {
          console.log('收入', res.data)
        })
      )

      // 清空数据
      this.items = []
      promise.push(
        // 分账汇总
        this.axios.get(`/officer/settle-items`, { params: {
          '@filter': `entity.getSettle().getOrderItem().getOrder().getCreatedTime() >= datetime.get('${this.search.date[0]} 08:00:00')
                    && entity.getSettle().getOrderItem().getOrder().getCreatedTime() <= datetime.get('${nextDate} 07:59:59')`,
          '@select': `SUM(entity.amount) as amount, entity.profitType as profitType`,
          '@groupBy': `entity.profitType`
        }}).then((res) => {
          res.data.sort((a, b) => {
            return a.profitType - b.profitType
          })
          this.items = res.data
        })
      )
      Promise.all(promise).then(res => {
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.background {
  background-color: #f0f0f0;
  padding: 15px 15px 15px 15px;
  border-radius: 10px;
}
.detail {
  background-color: white;
  padding: 20px;
  text-align: center;
}
.text {
  font-size: 24px;
  padding-top: 10px;
}
.box {
  padding: 10px;
  border:#666666 1px solid;
  border-radius: 10px;
  font-size: 24px;
  display: flex;
}
.item {
  padding: 10px 0px;
  display: flex;
  align-items: center;
}
</style>
